<?php
define('V2EX_BABEL', 1);

require_once ('core/Settings.php');

session_start();

include(BABEL_PREFIX . '/res/supported_languages.php');

if (isset($_SESSION['babel_lang'])) {
	if (in_array($_SESSION['babel_lang'], array_keys($_languages))) {
		define('BABEL_LANG', $_SESSION['babel_lang']);
	} else {
		define('BABEL_LANG', BABEL_LANG_DEFAULT);
	}
} else {
	define('BABEL_LANG', BABEL_LANG_DEFAULT);
}

require_once ('core/Vocabularies.php');
require_once ('core/Utilities.php');
require_once ('core/Shortcuts.php');
require_once('core/LanguageCore.php');

// New age lightweight functions.
require_once ('inc/check_login.php');

// PEAR.
ini_set('include_path', BABEL_PREFIX . '/libs/pear' . PATH_SEPARATOR . ini_get('include_path'));
require_once('Crypt/Blowfish.php');

if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
	$db = mysql_connect(BABEL_DB_HOSTNAME . ':' . BABEL_DB_PORT, BABEL_DB_USERNAME, BABEL_DB_PASSWORD);
	if ($db) {
		mysql_select_db(BABEL_DB_SCHEMATA);
		mysql_query("SET NAMES utf8");
		mysql_query("SET CHARACTER SET utf8");
		mysql_query("SET COLLATION_CONNECTION='utf8_general_ci'");
	}
	$rt = vx_check_login();
	if ($rt['errors'] == 0) {
		$bf = new Crypt_Blowfish(BABEL_BLOWFISH_KEY);
		setcookie('babel_usr_email', $rt['usr_email_value'], time() + 2678400, '/', BABEL_DNS_DOMAIN);
		setcookie('babel_usr_password', $bf->encrypt(sha1($rt['usr_password_value'])), time() + 2678400, '/', BABEL_DNS_DOMAIN);
		$_SESSION['babel_usr_email'] = $rt['usr_email_value'];
		$_SESSION['babel_usr_password'] = sha1($rt['usr_password_value']);
		$rt['mode'] = 'ok';
		if (trim($rt['return']) != '') {
			if (preg_match('/logout/i', $rt['return'])) {
				header('Location: /');
				die();
			} else {
				header('Location: ' . $rt['return']);
				die();
			}
		}
	} else {
		$rt['mode'] = 'error';
	}
	mysql_close($db);
} else {	
	$rt = array();
	$rt['mode'] = 'welcome';
	$rt['errors'] = 0;
}

require_once(BABEL_PREFIX . '/lang/' . BABEL_LANG . '/lang.php');

$lang = new lang();
if(isset($_POST['do']) && !empty($_POST['do'])){
	$json_array = array();
	if(is_valid_email($_POST['email'])){   
    $guid = md5($_POST['email'].microtime());
    $email = $_POST['email'];
    $sql = "SELECT usr_id FROM `babel_user` WHERE usr_email='$email'";
    $usr_id = @mysql_result(@mysql_query($sql, $db), 0);
    if(isset($usr_id) && !empty($usr_id)){
      $json_array = array('errno' => 3, 'errstr' => 'reg_email_repeat');
    }else{
      $sql = "SELECT guid FROM `babel_reg_email` WHERE email='$email'";
      $have_one = mysql_result(mysql_query($sql, $db), 0);
      if(isset($have_one) && !empty($have_one)){
        $sql = "UPDATE `babel_reg_email` SET guid='$guid' WHERE guid='$have_one'";
      }else{
        $sql = "INSERT INTO `babel_reg_email`(guid, email) VALUES('$guid', '$email')";
      }
      mysql_query($sql, $db);
      if(mysql_affected_rows($db)>0){
        $mail['subject'] = '['.Vocabulary::site_name.'] Register Email';
        $mail['body'] = "Click this link to continue.\nhttp://" . BABEL_DNS_NAME ."/signin/$guid.html";
        $am = new Airmail($email, $mail['subject'], $mail['body'], NULL);
        $am->vxSend();
        $am = null;
        $json_array = array('errno' => 0, 'errstr' => 'reg_email_sended');
      }else{
        $json_array = array('errno' => 2, 'errstr' => 'reg_email_error');
      }
    }
	}else{
		$json_array = array('errno' => 1, 'errstr' => 'reg_email_not_valid');
	}
	echo json_encode($json_array);exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 TRANSITIONAL//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title><?php echo Vocabulary::site_name . " " . $lang->register()?></title>
<link href="/css/login.css" media="screen" rel="stylesheet" type="text/css" />
<script src="/js/mootools.js" type="text/javascript"></script>
<?php
if (MINT_LOCATION != '') {
	echo('<script src="' . MINT_LOCATION . '" type="text/javascript"></script>');
}
?>
</head>
<?php
switch ($rt['mode']) {
	case 'welcome':
	default:
?>
<body onload="document.forms[0].elements[0].focus();">
<div id="main" align="center">

	<div id="v2ex" align="left">
		<div class="title"><?php echo Vocabulary::site_name ?> <?php echo $lang->register(); ?></div>
		<?php _v_hr() ?>
			<form action="signup.html" method="post" id="signupform" name="signupform">
      <table width="100%" cellpadding="5" cellspacing="0" class="login_form_t">
			<tr>
				<td width="80" align="right"><?php echo $lang->email(); ?></td>
				<td align="left" id="email_msg"><input name="email" type="text" class="line" onfocus="this.style.borderColor = '#0C0'; this.style.backgroundColor = '#FFF';" onblur="this.style.borderColor = '#999'; this.style.backgroundColor = '#F5F5F5';" maxlength="100" /></td>
			</tr>
			<tr>
				<td width="80"><input type="hidden" name="do" value="sendregmail" /></td>
				<td valign="middle"><span class="requesting" id="requestid"></span><input type="image" name="register_btn" src="/img/graphite/register_<?php echo BABEL_LANG ?>.gif" alt="<?php echo $lang->register(); ?>" /></td>
			</tr>
      </table>
			</form>
	</div>
	
	<div id="bottom" align="center">
	&copy; 2006-2007 <a href="http://<?php echo BABEL_DNS_NAME ?>/" target="_self"><?php echo Vocabulary::site_name ?></a>
	</div>

</div>
<script src="/js/lang.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
//<![CDATA[
	$('signupform').addEvent('submit',function(e){
		new Event(e).stop();
		if(this.email.value!="" && !this.email.disabled){
			$('requestid').setHTML(js_lang['reg_email_request']);
			$('requestid').addClass('ajax-loading');
			this.send({
				onComplete:function(responseText){
					//alert(responseText);
					$('requestid').removeClass('ajax-loading')
					eval("var jsonObj = "+responseText+";");
					$('requestid').addClass('request-msg');
          if(jsonObj.errno == "0"){
          	document.forms['signupform'].email.disabled = true;
            $('requestid').setHTML(js_lang[jsonObj.errstr]);
          }else{
            $('requestid').setHTML(js_lang[jsonObj.errstr]);
          }
				}
			});
		}
	});

//]]>
</script>
</body>
<?php
	break;
} // End: switch ($rt['mode'])
?>
</html>
